package com.export.thread;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.export.bean.model.StateModel;
import com.export.config.FileHandle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * Created by MeowParse on 2017/5/9.
 * 生成csv文件,并压缩为zip文件
 */
@Component("ActionThread")
@Scope("prototype")
public class ActionThread extends Thread{

    private static final Logger logger = LoggerFactory.getLogger(ActionThread.class);

    private List exportData;
    private String[] fileds;
    private LinkedHashMap map;
    private String outPutPath;
    private String fileName;
    private StateModel stateModel;

    public ActionThread(List exportData, String[] fileds, LinkedHashMap map, String outPutPath,
                        String fileName, StateModel stateModel) {
        this.exportData = exportData;
        this.fileds = fileds;
        this.map = map;
        this.outPutPath = outPutPath;
        this.fileName = fileName;
        this.stateModel = stateModel;
    }

    @Override
    public void run() {
        File csvFile = createCSVFile(exportData,fileds,map,outPutPath,fileName,stateModel);
        FileHandle.deleteFile(csvFile.getPath());
        stateModel.minusActNum();
        exportData.clear();
    }

    public static File createCSVFile(List exportData, String[] fileds,
                                     LinkedHashMap map, String outPutPath, String fileName,StateModel stateModel) {
        File csvFile = null;
        BufferedWriter csvFileOutputStream = null;
        try {
            // 定义文件名格式并创建
            csvFile = new File(outPutPath+fileName+".csv");
            logger.info("csvFile：" + csvFile);
            logger.info("fileName：" + fileName);
            csvFile.createNewFile();
            // UTF-8使正确读取分隔符","
            csvFileOutputStream = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(csvFile), "GBK"), 1024);
            logger.info("csvFileOutputStream：" + csvFileOutputStream);
            // 写入文件头部
            for (Iterator propertyIterator = map.entrySet().iterator(); propertyIterator
                    .hasNext();) {
                java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator
                        .next();
                csvFileOutputStream
                        .write((String) propertyEntry.getValue() != null ? new String(
                                ((String) propertyEntry.getValue())
                                        .getBytes("GBK"), "GBK") : "");
                if (propertyIterator.hasNext()) {
                    csvFileOutputStream.write(",");
                }
            }
            csvFileOutputStream.write("\r\n");

            // 写入文件内容,
            // ============ //第一种格式：Arraylist<实体类>填充实体类的基本信息==================
            for (int j = 0; exportData != null && !exportData.isEmpty()
                    && j < exportData.size(); j++) {

                JSONObject t = JSONObject.parseObject(JSON.toJSONString(exportData.get(j)));
//                DeviceKvHistoryModel t = (DeviceKvHistoryModel) exportData.get(j);
//                Class clazz = t.getClass();
                String[] contents = new String[fileds.length];
                for (int i = 0; fileds != null && i < fileds.length; i++) {
                    String filedName = (fileds[i]);
//                    Method method = clazz.getMethod(filedName);
//                    method.setAccessible(true);
//                    Object obj = method.invoke(t);
//                    String str = String.valueOf(obj);
                    String str = t.getString(filedName);
                    if (str == null || str.equals("null"))
                        str = "";
                    contents[i] = str;
                }
                for (int n = 0; n < contents.length; n++) {
                    // 将生成的单元格添加到工作表中
                    csvFileOutputStream.write(contents[n]);
                    csvFileOutputStream.write(",");
                }
                csvFileOutputStream.write("\r\n");
            }


            csvFileOutputStream.flush();
            FileHandle.ZipFile(csvFile.getPath(),csvFile.getAbsolutePath().replace(".csv",".zip"));

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                csvFileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        stateModel.setState();
        logger.info("compressive state/压缩状态:There are "+stateModel.getState()+" files to complete compression");
        return csvFile;
    }
}
